import { Button, Drawer, Form, Input, Modal, Spin } from "antd"
import { useForm } from "antd/lib/form/Form";
import { useEffect } from "react";
import { ErrorBox } from "../../components/lib";
import { TaskTypeSelect } from "../../components/task-type-select";
import { UserSelect } from "../../components/user-select";
import { useAddTask, useDeleteTask, useEditTask } from "../../utils/task";
import { useTaskModal, useTasksQueryKey } from "./util"

export const TaskModal = () => {
  const { taskModalOpen, isLoading, editingTask, editingTaskId, close } = useTaskModal();

  const [form] = useForm();

  const useMutateTask = editingTask ? useEditTask : useAddTask
  const { mutateAsync, isLoading: mutateLoading, error } = useMutateTask(useTasksQueryKey())

  const onFinish = (values: any) => {
    mutateAsync({...editingTask, ...values}).then(()=>{
      form.resetFields();
      close();
    })
  }

  const onClose = () => {
    form.resetFields();
    close();
  }

  const { mutate: deleteTask } = useDeleteTask(useTasksQueryKey());

  const onDelete = () => {
    close();
    Modal.confirm({
      okText: "确定",
      cancelText: "取消",
      title: "确定删除任务吗",
      onOk() {
        return deleteTask({ id: Number(editingTaskId) });
      },
    });
  }

  const title = editingTask ? '编辑任务' : '创建任务'

  useEffect(() => {
    form.setFieldsValue(editingTask);
  }, [form, editingTask]);

  return <Drawer
    forceRender={true}
    placement="right"
    closable={true}
    onClose={onClose}
    visible={taskModalOpen}
    width={'100%'}
  >
    {
      isLoading ?
        <Spin size="large" /> :
        <>
          <h1>{title}</h1>
          <ErrorBox error={error} />
          <Form form={form} layout={'vertical'} style={{ width: '40rem' }} onFinish={onFinish}>
            <Form.Item label={'任务名称'} name={'name'} rules={[{ required: true, message: '请输入任务名称' }]}>
              <Input placeholder={'请输入任务名称'} />
            </Form.Item>
            <Form.Item label={'经办人'} name={'processorId'} rules={[{ required: true, message: '请选择经办人' }]}>
              <UserSelect defaultOptionName={'经办人'} />
            </Form.Item>
            <Form.Item label={'类型'} name={'typeId'} rules={[{ required: true, message: '请选择类型' }]}>
              <TaskTypeSelect defaultOptionName={"类型"} />
            </Form.Item>
            <Form.Item style={{ textAlign: "right" }}>
              <Button loading={mutateLoading} type={'primary'} htmlType={'submit'}>提交</Button>
            </Form.Item>
          </Form>
          <Button onClick={onDelete}>删除事务</Button>
        </>
    }
  </Drawer>
}

